import axios from 'axios';
import type {AxiosInstance} from 'axios';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '@/stores/auth';


const request: AxiosInstance = axios.create({
    //baseURL: 'https://mock.mengxuegu.com/mock/65f78986838cf807b819d3fe/micro-app',
    //baseURL: '/dev-api',
    baseURL: import.meta.env.VITE_APP_BASE_API as string,
    timeout: 20000,

})
request.interceptors.request.use((config)=>{
     //console.log('请求拦截器', config);
    // 发送请求前在请求头加上token令牌
    const authStore = useAuthStore();
    const accessToken = authStore.accessToken;
    if (accessToken) {
        // oauth2 请求头带上令牌  Authorization: Bearer xxx
        config.headers.Authorization = 'Bearer '+ accessToken;
    }

    return config;
}, (error)=>{
    return Promise.reject(error);
});

request.interceptors.response.use((response)=>{
    //console.log('响应拦截器',response)
    const {data} = response;
    if(data.code === 200){
        return data;
    }
    ElMessage.error(data.msg || '请求失败');
    return Promise.reject(response);
}, (error)=>{
    console.log('response异常',error)
    const {message , response} = error;
    if(message.indexOf('401') != -1) {
        ElMessage.error('权限过期，请重新登录!')
        const authStore = useAuthStore();
        authStore.userLogout();
        return
    }else if(message.indexOf('timeout') != -1){
        ElMessage.error('网络超时!')
    }else if(message ==  'Network Error'){
        ElMessage.error('网络连接错误！')
    }else{

        if(response.data) ElMessage.error(response.statusText);
        else ElMessage.error('接口路径找不到！')
    }
    return Promise.reject(error);
});

export default request;
